package com.github.thinwonton.spring.datasource;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.RandomUtils;

import com.github.thinwonton.spring.entity.User;

/**
 * 用户数据源
 * 
 * @author hugo
 *
 */
public class UserDataSource {
	private static String[] chineseName = { "骏诚", "平星", "辰奇", "仕休", "信运", "初运", "骞骞", "材佳", "文家", "运宇", "锐振", "梁韦",
			"彬栋", "骏鸿", "振权", "然星", "辰梁", "良星", "炳驰", "嘉休", "桓礼", "卓运", "驰平", "颜华", "然枫", "运驰", "星郁", "骏鹤", "锐辰", "奇骏",
			"然骏", "爵博", "强逸", "晓祜", "琛逸", "林桓", "子福", "凡禧", "栋梓", "烁锟", "逸爵", "胤强", "翱鸿", "年晨", "轩骞", "爵驰", "平侠", "炳博",
			"康运", "加郁", "嘉槐", "禧鹏", "升桓", "澄恒", "谷皓", "林骏", "凡震", "裕轩", "博远", "杞栋", "芃祜", "中楷", "振凯" };

	private static List<User> users = new ArrayList<>();
	static {
		// 初始化数据
		int count = 10;
		for (int index = 0; index < count; index++) {
			User user = new User();
			user.setId(IDGenerator.get());
			user.setAge(RandomUtils.nextInt(1, 50));
			user.setName(randomChineseName());
			users.add(user);
		}
	}

	private static class IDGenerator {
		private static long id = 0;

		public static long get() {
			return ++id;
		}
	}

	private static String randomChineseName() {
		return chineseName[RandomUtils.nextInt(0, chineseName.length - 1)];
	}

	/**
	 * 获取指定ID的用户
	 * 
	 * @param id
	 * @return
	 */
	public static User getById(long id) {
		for (User user : users) {
			if (user.getId().longValue() == id) {
				return user;
			}
		}
		return null;
	}

	public static void save(User user) {
		user.setId(IDGenerator.get());
		users.add(user);
	}

	public static List<User> getUserList() {
		return users;
	}

	public static int update(User user) {
		User data = getById(user.getId());
		if (data != null) {
			data.setAge(user.getAge());
			data.setName(user.getName());
			return 1;
		} else {
			return 0;
		}
	}

	public static int delete(long id) {
		User data = getById(id);
		if (data != null) {
			users.remove(data);
			return 1;
		}
		return 0;
	}

}
